//页面数据模型
var viewMode = {};

var isAdmin = false;
var addFlag=true;
var updateFlag=true;
var deptInfo = {
    deptTreeIds : "",
    deptData : [],
    deptEditData : [],

    init : function() {
        // KO绑定
        viewMode = {
            isAdmin : ko.observable()
        };

        var datas = deptInfo.getDeptOrgData();
        deptInfo.deptData = datas;

        viewMode.isAdmin(isAdmin);
        ko.applyBindings(viewMode);

        // 初始化按钮
        setMenuButtonOpermission();

        // 初始化下拉树控件
        deptInfo.initCombotree($("#addPdeptId"), datas);
        deptInfo.initCombotree($("#editPdeptId"), datas);

        // 加载表单数据
        deptInfo.loadData();
        // 初始化事件绑定
        deptInfo.evenBind();

    },
    // 初始化添加部门div
    initAddDeptDiv : function() {
        // 页面数据模型
        viewMode = {
            isAdmin : ko.observable()
        };

        viewMode.isAdmin(isAdmin);
        ko.applyBindings(viewMode);

    },
    // 事件绑定
    evenBind : function() {

        // ----------------------------------------------------------------------->
        // 初始化
        // ----------------------------------------------------------------------->
        // 折叠
        $('#collapseAllDept').bind("click", function() {
            $("#listDataEx1").treegrid("collapseAll");
        });

        $("#btnSearch").bind("click", function() {
            $("#listDataEx1").treegrid("unselectAll");
            deptInfo.loadData();
        });
        // ----------------------------------------------------------------------->
        // 添加部门
        // ----------------------------------------------------------------------->
        $('#add').bind('click', function() {
            $('#createDeptForm').form('clear');
            $('#createDeptDiv').window('open');
            //addFlag=true;
        });

        // 取消
        $('#cancelCreateDept').bind('click', function() {
            $('#createDeptDiv').window('close');
            $('#createDeptForm').form('clear');
        });

        // 提交
        $('#submitCreateDept').bind('click', function() {
        	if(addFlag){
        		addFlag=false;
        		var loginPwd = $("#addLoginpw").textbox("getValue");
            	var loginPwdEncryption = deptInfo.doSM3(loginPwd);
    			$("#addLoginpw").textbox("setValue",loginPwdEncryption);
    			$("#addconfirmPW").textbox("setValue",loginPwdEncryption);
                $('#createDeptForm').form('submit', {
                    url : getProjectUrl('/bfs/dept/add'),
                    onSubmit : function() {
                    	addFlag=true;
                        var _flag = $(this).form('validate');
                        if (!_flag) {
                            return false;
                        }
                        var addDeptName = $('#addDeptName').val();
                        var addLoginname = $('#addLoginname').val();
                        var _valid = deptInfo.validDeptName(null, addDeptName);
                        var _validLoginName = deptInfo.validLoginName(null, addLoginname);
                        if (!_valid) {
                            $.messager.alert('提示', '部门名称已存在或为空!', 'warning');
                            return false;
                        }
                        if (!_validLoginName) {
                            $.messager.alert('提示', '管理员名称已存在或为空!', 'warning');
                            return false;
                        }
                        addFlag=false;
                        return true;
                    },
                    success : function(data) {
                        $.resultHandler(data, function() {
                            $('#createDeptForm').form('clear');
                            $('#createDeptDiv').dialog('close');
                        });
                        $("#searchDeptName").textbox('clear');
                        // 加载表单数据
                        deptInfo.loadData();
                       /* $('#listDataEx1').treegrid('load', {
                            searchDeptName : ''
                        });*/
                        deptInfo.refreshCombotree();
                        addFlag=true;
                    }
                });
        	}
        });

        $('#submitEditSelfDept').bind("click", function() {
        	$.messager.alert('提示', '不能修改自己所属部门!', 'warning');
        });
        
        // ----------------------------------------------------------------------->
        // 批量删除部门
        // ----------------------------------------------------------------------->
        $('#deletes').bind('click', function() {
        	//var datas = $('#listDataEx1').treegrid('getData');
            // var deptIds = deptInfo.getTreeIds(datas);
        	var datas= $('#listDataEx1').datagrid("getChecked");
            var deptIds = "";
            for(var i=0;i<datas.length;i++){
            	deptIds += datas[i].deptId+",";
            }
            if (!deptIds) {
                $.messager.alert('提示', '请先选中记录!', 'warning');
                return;
            }

            var _msg = '您确定要删除选中的记录吗?<br/><font color="red">该操作会删除部门和旗下的所有部门</fond>';
            $.messager.confirm('提示', _msg, function(r) {
                if (r) {
                    ajaxProcess({
                        url : getProjectUrl('/bfs/dept/drop'),
                        data : {
                            deptIds : deptIds
                        },
                        requestType : 'POST',
                        traditional : true,
                        successHandle : function(data) {
                            $.resultHandler(data, function() {
                                $('#listDataEx1').treegrid('reload');
                            });
                            deptInfo.refreshCombotree();
                        }
                    });

                    
                }
            });
        });

        // ----------------------------------------------------------------------->
        // 修改部门
        // ----------------------------------------------------------------------->
        // 取消
        $('#cancelEditDept').bind('click', function() {
            $('#editDeptForm').form('clear');
            $('#editDeptDiv').window('close');
        });

        $("#cancelEditSelfDept").bind('click', function() {
            $('#editSelfDeptForm').form('clear');
            $('#editSelfDeptDiv').window('close');
        });
        
        // 提交
        $('#submitEditDept').bind('click', function() {
        	if(updateFlag){
        		updateFlag=false;
        		$('#editDeptForm').form('submit', {
                    url : getProjectUrl('/bfs/dept/edit'),
                    onSubmit : function() {
                    	updateFlag=true;
                        var _flag = $(this).form('validate');
                        if (!_flag) {
                            return false;
                        }
                        var editDeptName = $('#editDeptName').val();
                        var editDeptId = $('#editDeptId').val();
                        var _valid = deptInfo.validDeptName(editDeptId, editDeptName);
                        if (!_valid) {
                            $.messager.alert('提示', '部门名称已存在或为空!', 'warning');
                            return false;
                        }
                        updateFlag=false;
                        return true;
                    },
                    success : function(data) {
                        $.resultHandler(data, function() {
                            $('#editDeptForm').form('clear');
                            $('#editDeptDiv').dialog('close');
                        });
                        $('#listDataEx1').treegrid('reload');
                        deptInfo.refreshCombotree();
                        updateFlag=true;
                    }
                });
        	}

        });
    },
    findParent : function(data, id) {
        var parentId;
        var isChild = false;
        for (var i = 0; i < data.length; i++) {
            if (data[i].parentId === "" || data[i].id === id) {
                parentId = data[i].id;
                if (data[i].children.length > 0) {
                    for (var j = 0; j < data[i].children.length; j++) {
                        if (data[i].children[j].id === id) {
                            isChild = true;
                            break;
                        } else {
                            isChild = deptInfo.findChild(data[i].children[j], id);
                            if (isChild) {
                                break;
                            }
                        }
                    }
                }
                if (isChild) {
                    break;
                }
            }
        }
        return parentId;
    },
    //sm3加密
    doSM3 : function(msg) {
		var msgData = CryptoJS.enc.Utf8.parse(msg);

		var md;
		var sm3keycur = new SM3Digest();
		msgData = sm3keycur.GetWords(msgData.toString());
		sm3keycur.BlockUpdate(msgData, 0, msgData.length);
		var c3 = new Array(32);
		sm3keycur.DoFinal(c3, 0);
		var hashHex = sm3keycur.GetHex(c3).toString();
		return hashHex.toUpperCase();
	},
    findChild : function(data, id) {
        var isChild = false;
        if (data.children.length > 0) {
            for (var j = 0; j < data.children.length; j++) {
                if (data.children[j].id === id) {
                    isChild = true;
                    break;
                } else {
                    deptInfo.findChild(data.children[j], id);
                }
            }
        } else {
            if (data.id === id) {
                isChild = true;
            }
        }
        return isChild;
    },
    // 初始化用户下拉框
    initUserCombobox : function(DOM) {
        var datas = deptInfo.getUserData();

        DOM.combobox({
            valueField : 'userid',
            textField : 'username',
            data : datas
        });

    },
    // 获取用户数据
    getUserData : function() {
        var result = [];

        ajaxProcess({
            url : getProjectUrl('/bfs/user/combobox'),
            data : {
                ustatus : 1
            },
            requestType : 'POST',
            async : false,
            successHandle : function(data) {
                result = data;
            }
        });

        return result;
    },
    refreshCombotree : function() {
        var datas = deptInfo.getDeptOrgData();
        deptInfo.deptData = datas;
        deptInfo.initCombotree($("#addPdeptId"), datas);
        deptInfo.initCombotree($("#editPdeptId"), datas);
    },
    // 获取部门组织树
    getDeptOrgData : function() {
        var result = [];

        ajaxProcess({
            url : getProjectUrl('/bfs/dept/combobox'),
            requestType : 'POST',
            async : false,
            successHandle : function(data) {
                if (data.message === "true") {// 确定是否admin
                    isAdmin = true;
                    result.push({id:"",text:"无上级部门"});
                }
                for (var i = 0; i < data.rows.length; i++) {
                    result.push(data.rows[i]);
                }
            }
        });

        return result;
    },
    // 初始化树下拉框
    initCombotree : function(DOM, data) {

        DOM.combotree({
            data : data
        });

    },
    initEditCombotree : function(DOM, data) {
        DOM.combotree({
            onBeforeSelect : function(node) {
                var id = node.id;

                var editId = $("#editDeptId").val();
                if (id === editId) {
                    DOM.combotree("unselect");
                }

            },
            data : data
        });
    },
    // -----------------------------------------------------------------------<
    // ----------------------------------------------------------------------->
    // 修改部门
    // ----------------------------------------------------------------------->
    openEditDeptDiv : function(id) {
        var $node = $('#listDataEx1').treegrid('find', id);
        if (!isAdmin) {
            // 如果节点没有父节点或者节点的父节点在页面上找不到,则不允许更改父节点
            var parentDeptName;
            if (!$node.parentId) {
                parentDeptName = "无上级部门";
            } else {
                var parentDeptNode = $('#listDataEx1').treegrid('find', $node.parentId);
                if (!parentDeptNode) {
                    var deptData = deptInfo.getDeptInfoData($node.parentId);
                    parentDeptName = deptData[0].deptName;
                }
            }
            if (parentDeptName) {
                $('#editSelfDeptDiv').window({
                    onOpen : function() {
                        deptInfo.initUserCombobox($('#selectEditSelfDeptLeaderName'));
                        $('#editSelfDeptForm').form('load', $node);

                        $('#editSelfPdeptId').combotree({
                            value : parentDeptName,
                            disabled : true
                        });
                    }
                });
                $('#editSelfDeptDiv').window('open');
                return;
            }
        }
        $('#editDeptDiv').window({
            onOpen : function() {
                deptInfo.initUserCombobox($('#selectEditDeptLeaderName'));

                deptInfo.deptEditData = deepClone(deptInfo.deptData);

                // 设置部门id及其子树不展示的数据
                var setSpecifiedDeptData = function(datas, id) {
                    for (var i = 0; i < datas.length; i++) {
                        if (datas[i].id === id) {
                            datas.splice(i, 1);
                            continue;
                        }
                        if (datas[i].children) {
                            setSpecifiedDeptData(datas[i].children, id);
                        }
                    }
                }

                setSpecifiedDeptData(deptInfo.deptEditData, id);

                deptInfo.initCombotree($("#editPdeptId"), deptInfo.deptEditData);

                $('#editDeptForm').form('load', $node);

                // 初始化下拉框的展示。combotree的id找不到显示id
                var parantNode = $("#editPdeptId").combotree('tree').tree('find', $node.parentId); // 寻找父节点是否存在
                if (!parantNode) {// 不存在
                    $("#editPdeptId").combotree('setText', '');
                }
                if ($node.parentId === "") {// 选中“无上级部门 " 的数据
                    $("#editPdeptId").combotree('setValue', '');
                }

                var deptLeader = $('#selectEditDeptLeaderName').combobox('select', $node.deptLeaderId);
                if (!deptLeader) {
                    $('#selectEditDeptLeaderName').combobox('setText', '');
                }

            }
        });
        $('#editDeptDiv').window('open');
    },
    // 获取部门信息数据
    getDeptInfoData : function(deptId) {
        var result;
        ajaxProcess({
            url : getProjectUrl('/bfs/dept/query'),
            data : {
                deptId : deptId
            },
            requestType : 'POST',
            async : false,
            successHandle : function(data) {
                result = data;
            }
        });
        return result;
    },
    // ----------------------------------------------------------------------->
    // 删除部门
    // ----------------------------------------------------------------------->
    openRemoveDeptDiv : function(id) {
        var $nodes = $('#listDataEx1').treegrid('getChildren', id);
        var ids = id;
        for (var i = 0; i < $nodes.length; i++) {
            ids += "," + $nodes[i].id;
        }
        var _msg = '您确定要删除选中的记录吗?<br/><font color="red">该操作会删除部门和旗下的所有部门</fond>';
        $.messager.confirm('提示', _msg, function(r) {
            if (r) {
                ajaxProcess({
                    url : getProjectUrl('/bfs/dept/drop'),
                    data : {
                        deptIds : ids
                    },
                    requestType : 'POST',
                    traditional : true,
                    successHandle : function(data) {
                        $.resultHandler(data, function() {
                            $('#listDataEx1').treegrid('reload');
                            deptInfo.refreshCombotree();
                        });
                    }
                });
            }
        });
    },

    // 验证部门的名称
    validDeptName : function(_deptId, _deptName) {
        var _flag;
        ajaxProcess({
            url : getProjectUrl("/bfs/dept/valid"),
            data : {
                deptId : _deptId,
                deptName : _deptName
            },
            requestType : 'POST',
            async : false,
            successHandle : function(data) {
                _flag = data.result;
            }
        });
        return _flag;
    },
    // 初始化选择页面
    initDeptLeaderNameDiv : function() {
        $('#searchDeptLeaderName').searchbox('setValue', '');
        $('#selectDeptLeaderNameGrid').datagrid('load', {
            searchUserName : ''
        });
    },
    beforeLoad : function() {
        $('#createDeptDiv').dialog('destroy', true);
        $('#editDeptDiv').dialog('destroy', true);
    },
    // 验证用户的名称
    validLoginName : function(_userId, _loginName) {
        var _flag;

        ajaxProcess({
            url : getProjectUrl("/bfs/user/valid"),
            data :  {
                userid : _userId,
                loginname : _loginName
            },
            requestType : 'POST',
            async : false,
            successHandle : function(data) {
                _flag = data.result;
            }
        });

        return _flag;
    },
    loadData : function() {
    	$(".list").show();
		$(".nolist").hide();
        $('#listDataEx1').treegrid(
                {
                    url : getProjectUrl('/bfs/dept/list'),
                    queryParams : {
                        searchDeptName : $.trim($("#searchDeptName").val())
                    },
                    idField : 'id',
                    treeField : 'text',
                    columns : [ [
                            {
                                field : 'id',
                                checkbox : true
                            },
                            {
                                field : 'deptId',
                                title : 'ID',
                                width : 100,
                                hidden : true
                            },
                            {
                                field : 'text',
                                title : '部门名称',
                                align : 'left',
                                width : 100
                            },
                            {
                                field : 'deptDesc',
                                title : '部门职能描述',
                                width : 100
                            },
                            {
                                field : 'deptLeaderName',
                                title : '部门负责人',
                                width : 100
                            },
                            {
                                field : 'createTime',
                                title : '创建时间',
                                width : 100,
                            },
                            {
                                field : 'control',
                                title : '操作',
                                width : 100,
                                align : 'center',
                                formatter : function(value, row) {
                                    var control = '<a class="btn-edit"   style="height:24px;" name="edit" title="编辑"   href="javascript:void(0)" onclick="deptInfo.openEditDeptDiv(\'' + row.id
                                            + '\');"></a>';
                                    control += '<a class="btn-delete"   style="height:24px;"  name="delete" title="删除" href="javascript:void(0)" onclick="deptInfo.openRemoveDeptDiv(\'' + row.id
                                            + '\',\'' + row.deptId + '\');"></a>';
                                    return control;
                                }
                            } ] ],
                    singleSelect : false,
                    rownumbers : true,
                    method : 'POST',
                    fitColumns : true,
                    animate : true,
                    checkbox : false,
                    checkOnSelect : false,
                    onCheck : function(row) {
                        row.check = true;
                        deptInfo.checkChildNode(row.id);
                    },
                    onUncheck : function(row) {
                        row.check = false;
                        deptInfo.uncheckChildNode(row.id);
                    },
                    onClickRow : function(row) {
                        if (row.check) {
                            row.check = false;
                            $("tr[node-id=" + row.id + "] input[type=checkbox]")[0].checked = false;
                            deptInfo.uncheckChildNode(row.id);
                        } else {
                            row.check = true;
                            $("tr[node-id=" + row.id + "] input[type=checkbox]")[0].checked = true;
                            deptInfo.checkChildNode(row.id);
                        }
                    },
                    onLoadSuccess : function(row, data) {
                        setMenuButtonOpermission();

                        $('.menucls').linkbutton();
                        deptInfo.setSearchNode(data.rows);
                        if(data.rows === null || data.rows.length === 0){
							   $(".list").hide();
							   $(".nolist").css("height", $(".list").outerHeight()).show();	 
						}
                    }
                });
    },
    setSearchNode : function(datas) {
        for (var i = 0; i < datas.length; i++) {
            if (datas[i].searchNode) {
                $('#listDataEx1').treegrid('select', datas[i].id);
            }
            if (datas[i].children) {
                deptInfo.setSearchNode(datas[i].children);
            }
        }
    },
    checkChildNode : function(id) {
        var childNode = $("#listDataEx1").treegrid('getChildren', id);
        for (var i = 0; i < childNode.length; i++) {
            $("tr[node-id=" + childNode[i].id + "] input[type=checkbox]")[0].checked = true;
            childNode[i].check = true;
        }
    },
    uncheckChildNode : function(id) {
        var childNode = $("#listDataEx1").treegrid('getChildren', id);
        for (var i = 0; i < childNode.length; i++) {
            $("tr[node-id=" + childNode[i].id + "] input[type=checkbox]")[0].checked = false;
            childNode[i].check = false;
        }
    },
/*    // 获取树的id
    getTreeIds : function(datas) {
        deptInfo.deptTreeIds = "";

        var treeIds = function(treeData) {
            for (var i = 0; i < treeData.length; i++) {
                if (treeData[i].check) {
                    deptInfo.deptTreeIds += treeData[i].deptId + ",";
                }
                treeIds(treeData[i].children);
            }
        }

        treeIds(datas);

        deptInfo.deptTreeIds = deptInfo.deptTreeIds.substring(0, deptInfo.deptTreeIds.length - 1);
        return deptInfo.deptTreeIds;
    }*/
};

$(function() {
    resetSize();
    deptInfo.init();
});
